package main

import (
	_ "database/sql"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"net/http"
)

// 第一次提交
func Connection() *gorm.DB {
	open, err := gorm.Open("mysql", "root:123456@(127.0.0.1:3306)/test?charset=utf8&parseTime=true&loc=Local")
	fmt.Println(err)
	if err != nil {
		return nil
	}
	return open
}

type TestLog struct {
	Id     int    `json:"id" gorm:"column:id"`
	Sex    string `json:"sex" gorm:"column:sex"`
	Remark string `json:"remark" gorm:"column:remark"`
}

func (TestLog) TableName() string {
	return "test_log"
}

type Test2 struct {
	TestLog
	Id      int    `json:"id" gorm:"column:id"`
	Name    string `json:"name" gorm:"column:name"`
	Age     int    `json:"age" gorm:"column:age"`
	Address string `json:"address" gorm:"column:address"`
	Sex     string `json:"sex" gorm:"column:sex"`
}

func (Test2) TableName() string {
	return "test1"
}
func main() {
	g := gin.Default()
	g.POST("update", Update)
	err := g.Run()
	if err != nil {
		return
	}
}
func Update(ctx *gin.Context) {
	var test Test2
	ctx.ShouldBind(&test)
	db := Connection()
	row := db.Debug().Model(&Test2{}).Where("age=?", test.Age).Update(test).RowsAffected
	ctx.JSON(
		http.StatusOK,
		gin.H{
			"更新了行数": row,
		})
}
func Join() {
	db := Connection()
	var test []Test2
	db.Debug().Where("t.age>?", 16).Table("test1 t").Joins("inner join test_log l on t.sex=l.sex").Select("t.name,t.sex,t.address,t.age,l.remark").Scan(&test)
	j, err := json.Marshal(&test)
	if err == nil {
		fmt.Println(string(j))
	}
}
func FindIn() {
	db := Connection()
	var test []Test2
	db.Debug().Or("name = ?", "胡琪").Or("age=?", "23").Find(&test)
	j, err := json.Marshal(&test)
	if err == nil {
		fmt.Println(string(j))
	}

}
func FindWhere() {
	open := Connection()
	test := make([]Test2, 0)
	open.Debug().Where(&Test2{Name: "胡琪"}).Find(&test)
	fmt.Println(test)
}
func Find() {
	open := Connection()
	test := make([]Test2, 0)
	open.Debug().Where("name like ?", "%胡%").Find(&test)
	fmt.Println(test)
}
func First() {
	open := Connection()
	var test2 = new(Test2)
	open.Debug().First(test2)
	fmt.Println(test2)
}
func add() {
	open := Connection()
	// 创建表的语句，不需要
	// open.Debug().AutoMigrate(&Test2{})
	test2 := Test2{Name: "go2", Age: 26, Address: "42312"}
	open.Debug().Create(&test2)
}
